package huixue.cn.com.rxapp.interceptor;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import huixue.cn.com.library.util.HttpUtil;
import huixue.cn.com.library.util.LogUtils;
import huixue.cn.com.library.util.MD5;
import huixue.cn.com.rxapp.entity.DeviceInfo;
import okhttp3.FormBody;
import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by gongdongyang on 2018/7/27.
 */

public class CommonInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request oldRequest = chain.request();
        // 新的请求
        HttpUrl httpUrl = null;
        if (oldRequest.method().equals("GET")) {
            httpUrl = HttpUrl.parse(parseUrl(oldRequest.url().url().toString()));
            //addGetParamsSign();
        } else if(oldRequest.method().equals("POST")){
            httpUrl = oldRequest.url();
            oldRequest = addPostParamsSign(oldRequest);
        }
        return chain.proceed(oldRequest);
    }

    //解析前：https://xxx.xxx.xxx/app/chairdressing/skinAnalyzePower/skinTestResult?appId=10101
    //解析后：https://xxx.xxx.xxx/app/chairdressing/skinAnalyzePower/skinTestResult
    private String parseUrl(String url) {
        if (!"".equals(url) && url.contains("?")) {// 如果URL不是空字符串
            url = url.substring(0, url.indexOf('?'));
        }
        return url;
    }

    //添加参数和签名
    //post 添加签名和公共动态参数
    private Request addPostParamsSign(Request request) throws UnsupportedEncodingException {
        try{
            if (request.body() instanceof FormBody  ) {
                FormBody.Builder bodyBuilder = new FormBody.Builder();
                FormBody formBody = (FormBody) request.body();

                //原有的参数
                TreeMap<String, String> oldparams = new TreeMap<>();

                for(int i= 0; i < formBody.size(); i++){
                    oldparams.put(formBody.encodedName(i), formBody.encodedValue(i));
                }

                //拼装新的参数
                SortedMap<String, String> newParams = dynamic(oldparams);

                for (Map.Entry<String, String> entry : newParams.entrySet()) {
                    String value = URLDecoder.decode(entry.getValue(), HttpUtil.UTF8.name());
                    bodyBuilder.addEncoded(entry.getKey(), value);
                }

                formBody = bodyBuilder.build();
                request = request.newBuilder().post(formBody).build();
            } else if(request.method().equals("POST")){

            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            return request;
        }



    }

    public SortedMap<String ,String> dynamic(TreeMap<String, String> params){
        SortedMap<String, String> newParams = new TreeMap<>();
        for(Map.Entry<String,String> entry : params.entrySet()){
            newParams.put(entry.getKey(),entry.getValue());
        }
        newParams.put("unionid","unionid");
        newParams.put("deviceID", DeviceInfo.mDeviceID);
        newParams.put("versionID", DeviceInfo.mVersionID);
        newParams.put("source", "zcx");
        newParams.put("phoneType", DeviceInfo.mPhoneType);
        newParams.put("requireStr",System.currentTimeMillis() + "");
        StringBuffer sb = new StringBuffer("");
        for(Map.Entry<String,String> entry : newParams.entrySet()){

            sb.append(entry.getKey()).append(entry.getValue());
        }

        try{
            LogUtils.d(sb.toString());
            String sign = MD5.md5(sb.toString());
            newParams.put("sign",sign);
        }catch (Exception e){

        }

        return newParams;
    }

}
